<template>
  <div class="keycard-ranking">
    <!-- 顶部标题 -->
    <div class="header">
      <n-space align="center" :size="10">
        <n-icon :size="26" color="#d97706">
          <LockClosedOutline />
        </n-icon>
        <n-text strong style="font-size: 20px;">钥匙卡排行榜</n-text>
      </n-space>
    </div>

    <!-- 排行榜列表区域 -->
    <div class="ranking-section">
      <!-- 加载骨架屏 -->
      <LoadingSkeleton v-if="loading" type="list" :count="pageSize" />

      <!-- 空状态 -->
      <div v-else-if="!items.length" class="empty-wrapper">
        <n-empty description="暂无排行数据">
          <template #icon>
            <n-icon :size="48" :depth="3">
              <LockClosedOutline />
            </n-icon>
          </template>
        </n-empty>
      </div>

      <!-- 排行榜表格 -->
      <n-data-table
        v-else
        :columns="columns"
        :data="items"
        :pagination="false"
        :bordered="false"
      />

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="total > pageSize">
        <n-pagination
          :page="page"
          :page-size="pageSize"
          :item-count="total"
          show-size-picker
          :page-sizes="[10, 20, 30, 50]"
          @update:page="onPageChange"
          @update:page-size="onPageSizeChange"
        />
      </div>
    </div>

    <!-- 物品详情弹窗 -->
    <ItemDetailModal
      v-model:show="showDetailModal"
      :object-id="selectedItemId"
    />
  </div>
</template>

<script setup lang="ts">
// --------------- 依赖导入 ---------------
import { ref, onMounted, h } from 'vue'
import { NDataTable, NPagination, NIcon, NText, NEmpty, NAvatar } from 'naive-ui'
import { LockClosedOutline } from '@vicons/ionicons5'
import { getKeycardRanking } from '@/api/ranking'
import type { DataTableColumns } from 'naive-ui'
import type { KeycardRankingResponse, KeycardRankingItem } from '@/types/ranking'
import LoadingSkeleton from '../../../components/common/LoadingSkeleton.vue'
import ItemDetailModal from '../../../components/ItemDetailModal.vue'

// --------------- 类型定义 ---------------
interface KeycardItem {
  object_id: number
  name: string
  image_url: string
  grade: number
  current_price: number
  day_price: number
  day_change: number
  day_change_pct: number
  week_price: number
  week_change: number
  week_change_pct: number
  month_price: number
  month_change: number
  month_change_pct: number
}

// --------------- 响应式状态 ---------------
const loading = ref(false)
const items = ref<KeycardItem[]>([])
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 详情弹窗相关状态
const showDetailModal = ref(false)
const selectedItemId = ref<number | null>(null)

// --------------- 表格列定义 ---------------
const columns: DataTableColumns<KeycardRankingItem> = [
  {
    title: '排名',
    key: 'rank',
    width: 70,
    render: (_row, index) => {
      return index + 1 + (page.value - 1) * pageSize.value
    }
  },
  {
    title: '物品',
    key: 'name',
    render: (row) => {
      // 根据等级添加全局边框class
      return h('div', {
        style: {
          display: 'flex',
          alignItems: 'center',
          gap: '8px',
          cursor: 'pointer'
        },
        onClick: () => showItemDetail(row.object_id)
      }, [
        h(NAvatar, {
          size: 36,
          src: row.image_url,
          class: `grade-bg-${row.grade}`,
          style: {
            background: '#fff',
            marginRight: '4px'
          }
        }),
        h('span', { style: { fontWeight: 500 } }, row.name)
      ])
    }
  },
  {
    title: '当前价格',
    key: 'current_price',
    render: (row) => `${row.current_price.toFixed(2)}`
  },
  // 今日涨幅列
  {
    title: '今日涨幅',
    key: 'day_change',
    render: (row) => {
      const color = row.day_change > 0 ? '#f56c6c' : row.day_change < 0 ? '#67c23a' : '#909399'
      return h('span', { style: { color, fontWeight: 500 } }, `${row.day_change.toFixed(2)} ( ${row.day_change_pct.toFixed(2)}% )`)
    }
  },
  // 7 日数据
  {
    title: '7日价格',
    key: 'week_price',
    render: (row) => row.week_price.toFixed(2)
  },
  {
    title: '7日涨幅',
    key: 'week_change',
    render: (row) => {
      const color = row.week_change > 0 ? '#f56c6c' : row.week_change < 0 ? '#67c23a' : '#909399'
      return h('span', { style: { color, fontWeight: 500 } }, `${row.week_change.toFixed(2)} ( ${row.week_change_pct.toFixed(2)}% )`)
    }
  },
  // 30 日数据
  {
    title: '30日价格',
    key: 'month_price',
    render: (row) => row.month_price.toFixed(2)
  },
  {
    title: '30日涨幅',
    key: 'month_change',
    render: (row) => {
      const color = row.month_change > 0 ? '#f56c6c' : row.month_change < 0 ? '#67c23a' : '#909399'
      return h('span', { style: { color, fontWeight: 500 } }, `${row.month_change.toFixed(2)} ( ${row.month_change_pct.toFixed(2)}% )`)
    }
  }
]

// --------------- 方法 ---------------
// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    const resp = await getKeycardRanking({ page: page.value, page_size: pageSize.value })
    // 类型断言，兼容后端返回结构
    const data = resp.data as unknown as KeycardRankingResponse
    if (resp.code === 1 && data && Array.isArray(data.list)) {
      items.value = data.list
      total.value = data.total
    } else {
      items.value = []
      total.value = 0
    }
  } catch (err) {
    console.error('获取钥匙卡排行榜失败', err)
    items.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 分页变化
const onPageChange = (p: number) => {
  page.value = p
  fetchData()
}

const onPageSizeChange = (s: number) => {
  pageSize.value = s
  page.value = 1
  fetchData()
}

// 显示物品详情
const showItemDetail = (objectId: number) => {
  console.log('KeycardRanking: 点击显示物品详情, objectId:', objectId)
  selectedItemId.value = objectId
  showDetailModal.value = true
  console.log('KeycardRanking: 设置状态完成, selectedItemId:', selectedItemId.value, 'showDetailModal:', showDetailModal.value)
}

// 组件挂载时加载数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.keycard-ranking {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.ranking-section {
  background: var(--n-card-color);
  padding: 16px;
  border: 1px solid var(--n-border-color);
  border-radius: 8px;
}

.loading-wrapper,
.empty-wrapper {
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pagination-wrapper {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}
</style> 